using LogService.Interface;
using Microsoft.Data.Sqlite;

// SQLite 数据库日志记录器
namespace LogService.Implement;

public class DatabaseLogger : ILogger
{
    private const string ConnectionString = "Data Source=log.db";

    public DatabaseLogger()
    {
        InitializeDatabase();
    }

    // 初始化数据库并创建表
    private void InitializeDatabase()
    {
        using (var connection = new SqliteConnection(ConnectionString))
        {
            connection.Open();
            string createTableQuery = @"CREATE TABLE IF NOT EXISTS Logs (
                                        Id INTEGER PRIMARY KEY AUTOINCREMENT,
                                        Message TEXT NOT NULL,
                                        LogTime TEXT NOT NULL
                                    )";
            using (var command = new SqliteCommand(createTableQuery, connection))
            {
                command.ExecuteNonQuery();
            }
        }
    }

    // 插入日志到数据库
    public void Log(string message)
    {
        using (var connection = new SqliteConnection(ConnectionString))
        {
            connection.Open();
            string insertQuery = "INSERT INTO Logs (Message, LogTime) VALUES (@Message, @LogTime)";
            using (var command = new SqliteCommand(insertQuery, connection))
            {
                command.Parameters.AddWithValue("@Message", message);
                command.Parameters.AddWithValue("@LogTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                command.ExecuteNonQuery();
            }
        }
        Console.WriteLine("Database Log: " + message);
    }
}